package com.zzl.boot.bigevent.interceptor;

import com.zzl.boot.bigevent.utils.JWTUtils;
import com.zzl.boot.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String header = request.getHeader("Authorization");//获取请求头里的令牌
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            if(operations.get(header)==null){
                 throw new  Exception();
            }
            Map<String, Object> map = JWTUtils.verifyToken(header);//将用户id和用户名取出
            ThreadLocalUtil.set(map);//使用全局线程存map
            return true;//方行
        } catch (Exception e) {
            response.setStatus(401);
            return false;//拦截
        }
    }

    //请求完成后执行的代码
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();//清楚除hreadLocal中的数据，防止内存泄漏
    }
}
